package com.example.demo.oo.domain;

import com.example.demo.oo.domain.vo.HashId;
import com.example.demo.oo.domain.vo.Mobile;
import com.example.demo.oo.domain.vo.Nickname;
import com.example.demo.oo.domain.vo.Token;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Data
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "users")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;


    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "value",column = @Column(name = "mobile")),
    })
    //@JsonUnwrapped
    private Mobile mobile = new Mobile();

    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "value",column = @Column(name = "hash_id")),
    })
    private HashId hashId = new HashId();

    //@Column(insertable = false)
    private Integer money = 0;

    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "value",column = @Column(name = "token")),
    })
    private Token token = new Token();

    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "value",column = @Column(name = "nickname")),
    })
    private Nickname nickname = new Nickname();

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    @Column(name = "login_at", columnDefinition = "DATETIME")
    private LocalDateTime loginAt;


    @OneToMany(mappedBy ="userId", cascade=CascadeType.MERGE, fetch=FetchType.LAZY)
    //@JsonIgnoreProperties({"user"})
    private List<UserMoneyLog> moneyLogs = new ArrayList<>();


//     @OneToOne(mappedBy = "user", cascade = CascadeType.MERGE)
//    @JsonIgnoreProperties({"user"})
//    private UserMoneyLog moneyLog;



    public void reLogin() {

        // 更新登陆时间
        loginAt = LocalDateTime.now();
        // 重新生成token
        token.generate(mobile.getValue());
    }

    public void register() {

        // 更新登陆时间
        loginAt = LocalDateTime.now();
        // 生成token
        token.generate(mobile.getValue());
        // 生成昵称
        nickname.generate(mobile.getValue());
    }

    public void generateHashId() {
        String value = hashId.encode(id);
        hashId.setValue(value);
    }

    @JsonIgnore
    public boolean isRepo() {
        return id != null;
    }



    @PrePersist
    void preInsert() {

    }

    @PostLoad
    void postLoad() {
    }
}
